<template>
    <div style="width: 100%;" class="commonEntityDialog">
        <div class="dialogTitle">
            <el-tabs v-model="activeName">
                <el-tab-pane label="基本信息" name="1" disabled></el-tab-pane>
                <el-tab-pane label="接口" name="2" disabled></el-tab-pane>
                <el-tab-pane label="属性" name="3" disabled></el-tab-pane>
                <el-tab-pane label="功能配置" name="4" disabled></el-tab-pane>
                <el-tab-pane v-if="showComponent" label="关系" name="5" disabled></el-tab-pane>
            </el-tabs>
        </div>
        <div style="width: 100%" v-if="visible">
            <base-info :showThisTabs="showThisTabs" :show="activeName==='1'" ref="step1"></base-info>
            <interface :show="activeName==='2'" ref="step2"></interface>
            <properties :extendsAttribute.sync="allFormData.extendsAttribute"
                        :show="activeName==='3'"
                        ref="step3"></properties>
            <function @removeFunctionInterfaces="removeFunctionInterfaces" :show="activeName==='4'"
                      ref="step4"></function>
            <relation :show="activeName==='5'" ref="step5"></relation>
        </div>

        <div class="md-component-btns">
            <el-button size="medium" type="primary" v-if="dialogType==='view'"
                       @click="()=>{$emit('viewToEdit'),dialogType='edit'}">编辑
            </el-button>
            <el-button size="medium" v-if="activeName==='1'&&dialogType!=='view'" type="primary" @click="saveBaseInfo">
                保存
            </el-button>
            <el-button size="medium" v-if="activeName!=='1'" @click="changeStep(-1)">上一步</el-button>
            <el-button size="medium" :disabled="!saveFirst"
                       v-if="showComponent?activeName!=='5':activeName!=='4'"
                       @click="changeStep(+1)">下一步
            </el-button>
            <el-button size="medium" v-if="dialogType==='view'?false:(showComponent?activeName==='5':activeName==='4')"
                       type="primary" @click="saveAll">
                保存
            </el-button>
            <el-button size="medium" @click="$emit('removeThisTabs')">取消</el-button>
        </div>
    </div>
</template>

<script>
import BaseInfo from "@/views/DMDComponent/entityTemp/baseInfo.vue";
import Interface from "@/views/DMDComponent/entityTemp/Interface.vue";
import Properties from "@/views/DMDComponent/entityTemp/Properties.vue";
import Relation from "@/views/DMDComponent/entityTemp/Relation.vue";
import Function from "@/views/DMDComponent/entityTemp/Function.vue";

import * as entity from "@/api/modulManage/entity"
import * as relation from "@/api/modulManage/relation"

export default {
    name: "commonEntityTemp",
    components: {Function, Relation, Properties, Interface, BaseInfo},
    inject: ["temp"],
    provide() {
        return {
            allFormData: () => this.allFormData,
            dialogType: () => this.dialogType,
        }
    },
    props: {
        showThisTabs: {
            type: Boolean,
            default: () => {
                return false;
            }
        },
    },
    data() {
        return {
            visible: false,
            activeName: "",
            activeIndex: 0,

            EMTabs: ["1", "2", "3", "4", "5"],
            ERTabs: ["1", "2", "3", "4"],

            saveFirst: false,

            dialogType: "add",

            allFormData: {
                toOid: "",
                fromOid: "",
                implTypeInterfaces: [],
                functionInterfaces: [],
                functionTypeInterfaces: [],
                typeAttributes: [],
                extendsAttribute: []
            },

            api: {entity, relation}
        }
    },
    computed: {
        /**
         * 为关系实体（true）
         * */
        showComponent() {
            return this.temp === "EM";
        }
    },
    methods: {
        removeFunctionInterfaces(v) {
            this.allFormData.functionInterfaces.forEach(item => {
                if (item.oid === v.oid) {
                    item.settingsJson = "";
                }
            })
        },
        /**
         * 保存所有数据
         * */
        saveAll() {
            let api = this.showComponent ? "entity" : "relation";
            if (!this.showComponent) {
                let {form} = this.$refs['step4'].getTabData();
                this.getStep4Data(form);
                this.allFormData.fromOid = "," + this.allFormData.fromOid.join(",") + ",";
                this.allFormData.toOid = "," + this.allFormData.toOid.join(",") + ",";
            }

            this.$set(this.allFormData, "settingJsonUpdates", this.deepCopy(this.allFormData.functionTypeInterfaces))
            delete this.allFormData.functionInterfaces;

            this.api[api].update(this.allFormData).then(() => {
                this.$emit('removeThisTabs');
                this.$message.success("保存成功");
                this.$emit("refresh");
            })
        },
        /**
         * 保存基本信息
         * 保存了基本信息才可以下一步
         * */
        async saveBaseInfo() {
            let method = this.dialogType === "add" ? "add" : "update";
            let api = this.showComponent ? "entity" : "relation";

            let {form, flag} = await this.$refs["step1"].getTabData();
            Object.assign(this.allFormData, form);

            let data = form.functionInterfaces;
            let functionTypeInterfaces = []

            data.forEach(item => {
                // if (item.extendsFlag !== 1) {
                functionTypeInterfaces.push({
                    interfaceId: item.oid,
                    settingsJson: "",
                    extendsFlag: item.extendsFlag ? item.extendsFlag : 0,
                    oid: item.refId ? item.refId : ""
                })
                // }
            })
            if (!this.showComponent) {
                form.fromOid = "," + form.fromOid.join(",") + ",";
                form.toOid = "," + form.toOid.join(",") + ",";
            }
            if (flag) {
                let obj = {saveBaseInfoFlag: 0}
                if (method === "update") {
                    obj.saveBaseInfoFlag = 1;
                    let data = [];
                    if (this.allFormData.functionInterfaces && this.allFormData.functionInterfaces.length > 0) {
                        this.allFormData.functionInterfaces.forEach(item => {
                            data.push({
                                oid: item.refId,
                                settingsJson: item.settingsJson
                            })
                        })
                    }

                    this.allFormData.settingJsonUpdates = this.deepCopy(data);
                    delete this.allFormData.functionInterfaces;
                }
                this.api[api][method]({...form, functionTypeInterfaces, ...obj}).then((res) => {
                    this.saveFirst = true;
                    this.$message.success("保存成功");
                    this.edit({oid: res.data.data});
                })
            }
        },

        /**
         * @param v -1 上一步  +1 下一步
         * 关系实体（EM）和实体模型（ER）公用
         * */
        async changeStep(v) {
            let tabs = this.EMTabs;
            if (!this.showComponent) {
                tabs = this.ERTabs;
            }

            let {form, flag} = await this.$refs['step' + this.activeName].getTabData();

            if (flag) {
                switch (this.activeName) {
                    case "1":
                        Object.assign(this.allFormData, form);
                        Object.assign(this.allFormData, {step1: this.deepCopy(form), saveFirst: true});
                        break;
                    case "2":
                        let implTypeInterfaces = [];
                        if (!form && form.length === 0) {
                            break;
                        }
                        form.forEach(item => {
                            implTypeInterfaces.push({"interfaceId": item.oid});
                        })
                        Object.assign(this.allFormData, {implTypeInterfaces: implTypeInterfaces});
                        Object.assign(this.allFormData, {step2: this.deepCopy(form), saveStep2: true});
                        break;
                    case "3":
                        let typeAttributes = [];
                        if (!form && form.length === 0) {
                            break;
                        }
                        form.forEach(item => {
                            typeAttributes.push({"attributeId": item.oid});
                        })
                        Object.assign(this.allFormData, {typeAttributes: typeAttributes})
                        Object.assign(this.allFormData, {step3: this.deepCopy(form)})
                        break;
                    case "4":
                        this.getStep4Data(form);
                        break;
                }
            }

            this.activeName = tabs[this.activeIndex += v];
        },
        getStep4Data(form) {
            let functionInterfaces = [];
            if (form && form.length !== 0) {
                form.forEach(item => {
                    let obj = {};
                    obj.settingsJson = this.deepCopy(item.settingsJson);
                    obj.interfaceId = item.interfaceId;
                    functionInterfaces.push(obj)
                })

                let ids = functionInterfaces.map(item => item.interfaceId);

                if (this.allFormData.functionInterfaces && this.allFormData.functionInterfaces.length > 0) {
                    this.allFormData.functionInterfaces.forEach(item => {
                        let index = ids.indexOf(item.oid);
                        if (index === -1 && item.oid) {
                            functionInterfaces.push({
                                interfaceId: item.oid,
                                settingsJson: "",
                                oid: item.refId ? item.refId : ""
                            })
                        }
                    })

                    this.allFormData.functionInterfaces.forEach(item => {
                        let index = ids.indexOf(item.oid);
                        if (index !== -1) {
                            Object.assign(
                                functionInterfaces[index],
                                {extendsFlag: item.extendsFlag ? item.extendsFlag : 0},
                                {oid: item.refId ? item.refId : ""});
                        }
                    })
                }
                this.$set(this.allFormData, "functionTypeInterfaces", functionInterfaces);
                this.$set(this.allFormData, "step4", {step1: this.deepCopy(form), saveStep4: true});
            }
        },
        /**
         * @param row 查看 行内数据（row）
         * */
        view(row) {
            this.dialogType = "view";
            let api = this.showComponent ? "entity" : "relation";
            this.api[api].getDetail({oid: row.oid}).then(res => {
                this.visible = true;
                this.saveFirst = true;
                this.activeName = "1";
                this.activeIndex = 0;
                this.$nextTick(() => {
                    this.$refs['step1'].view_edit("view", res.data.data)
                    Object.assign(this.allFormData, res.data.data);
                })
            })
        },
        /**
         * @param row 编辑 行内数据（row）
         * */
        edit(row) {
            this.dialogType = "edit";
            let api = this.showComponent ? "entity" : "relation";
            this.api[api].getDetail({oid: row.oid}).then(res => {
                this.visible = true;
                this.saveFirst = true;
                this.activeName = "1";
                this.activeIndex = 0;
                this.$nextTick(() => {
                    this.$refs['step1'].view_edit("edit", res.data.data)
                    Object.assign(this.allFormData, res.data.data);
                })
            })
        },
        open() {
            this.visible = true;
            this.activeName = "1";
            this.activeIndex = 0;
            this.dialogType = "add";
            this.saveFirst = false;
        },
        close() {
            this.visible = false;
            this.allFormData = {};
        },
    },
    mounted() {
    },
    created() {
    },
    watch: {}
}
</script>

<style lang="scss">

.dialogTitle {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  flex-wrap: nowrap;

  > span {
    display: flex;
    flex-direction: column;
    justify-content: center;
  }

  .el-tabs {
    .el-tabs__header {
      margin: 0;

      .el-tabs__nav-wrap::after {
        height: 0;
      }

      .el-tabs__nav-wrap {
        .el-tabs__nav-scroll {
          .el-tabs__nav {
            .is-disabled {
              color: #303133;
            }

            .is-active {
              color: #409EFF !important;
            }
          }
        }
      }
    }
  }
}
</style>
